package com.yudean.esb.plugins;

import org.apache.ibatis.session.ResultContext;
import org.apache.ibatis.session.ResultHandler;

import java.util.*;

/**
 * 根据配置要求对其中内容进行更改
 *
 * @author : DL<duanlei@gdyd.com>
 * @version : 1.0
 */
public class MappedResultHandler implements ResultHandler {

    private List<Map<String, Object>> mapped = new ArrayList<Map<String, Object>>();
    private Map<String, String> mapper = null;
    private Set<String> keys = null;

    public MappedResultHandler(Map<String, String> mapper) {
        this.mapper = mapper;
        this.keys = mapper.keySet();
    }

    @SuppressWarnings("unchecked")
    @Override
    public void handleResult(ResultContext resultContext) {
        HashMap<String, Object> record = (HashMap<String, Object>) resultContext.getResultObject();

        Iterator<String> iterator = this.keys.iterator();
        HashMap<String, Object> result = new HashMap<String, Object>();
        while (iterator.hasNext()) {
            String oldKey = iterator.next();
            String newKey = this.mapper.get(oldKey);
            if (newKey == null) {
                continue;
            }
            Object obj = record.get(oldKey);
            //用来处理数据类型
            String dataVal = DbTypeHandler.getValue(obj);
            result.put(newKey, dataVal);
        }
        //清除对象
        record = null;
        mapped.add(result);
    }

    public List<Map<String, Object>> getResult() {
        return mapped;
    }
}
